package org.apmap.servlets;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.Hibernate;
import org.apmap.base.Flat;
import org.apmap.base.Main;
import org.apmap.base.User;
import org.apmap.forms.FlatForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetFlatAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
        FlatForm form = (FlatForm) actionForm;

        Session session = Main.getSession();
        Flat flat = (Flat) session.load(Flat.class, form.getFlatid());
        request.setAttribute("flat", flat);

        User user = (User) request.getSession().getAttribute("user");
        boolean owner = false;
        if (user != null && user.getId() == flat.getUser().getId()) {
            owner = true;
        }
        Hibernate.initialize(flat);
        Hibernate.initialize(user);

        session.close();

        return owner ? mapping.findForward("properties") : mapping.findForward("readonlyproperties");
    }

}